from flask import render_template, redirect, request, url_for, flash, jsonify
from flask_login import login_required

from . import main
from .. import db
from ..models import Dictionary, ICD, SNOMED
from .forms import SearchForm, AddForm, EditForm, DeleteWordForm


@main.route('/dictionary/index', methods=['GET', 'POST'])
def dictionary_index():
    form = SearchForm()
    diseases = []
    delete_word_form = DeleteWordForm(prefix='deleteWord')
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''
        disease = Dictionary.query.filter(Dictionary.name.like('%%%s%%' % name)).all()
        if disease is None:
            result = None
        else:
            for dis in disease:
                diseases.append({
                    'id': dis.id, 'code': dis.code, 'ICD_code': dis.ICD_code,'SNO_code':dis.SNO_code,
                    'name': dis.name, 'description': dis.description
                })
            result = diseases
        db.session.remove()
    else:
        disease = Dictionary.query.limit(200)
        print(disease)
        for dis in disease:
            diseases.append({
                'id': dis.id, 'code': dis.code, 'ICD_code': dis.ICD_code, 'SNO_code':dis.SNO_code,
                'name': dis.name, 'description': dis.description
            })
        result = diseases
        db.session.remove()
    if delete_word_form.validate_on_submit():
        db.session.query(Dictionary).filter_by(id=delete_word_form.id.data).delete()
    n = len(diseases)
    # print(n)
    db.session.remove()
    return render_template('dictionary/dictionary.html', form=form, result=result, n=n, deleteWordForm=delete_word_form)


@main.route('/dictionary/add-new-word', methods=['GET', 'POST'])
@login_required
def add_new_word():
    form = AddForm()
    if form.validate_on_submit():
        code = form.code.data
        ICD_code = form.ICD_code.data
        SNO_code = form.SNO_code.data
        name = form.name.data
        description = form.description.data
        disease = Dictionary.query.filter_by(code=code).first()
        disease1 = Dictionary.query.filter_by(name=name).first()
        if disease is None:
            if disease1 is None:
                new_disease = Dictionary(code=code, ICD_code=ICD_code, SNO_code=SNO_code,
                                         name=name, description=description)
                db.session.add(new_disease)
                return redirect(url_for('.index'))
            else:
                flash(u'该词已存在')
        else:
            flash(u'该编码已被占用')
    db.session.remove()
    return render_template('dictionary/add_new_word.html', form=form, R=CodeRange())


@main.route('/dictionary/edit/<word_id>', methods=['GET', 'POST'])
@login_required
def edit(word_id):
    disease = Dictionary.query.filter_by(id=word_id).first()
    form = EditForm(prefix='edit', obj=disease)
    if form.validate_on_submit():
        disease.code = form.code.data
        disease.ICD_code = form.ICD_code
        disease.SNO_code = form.SNO_code
        disease.name = form.name.data
        disease.description = form.description.data
        db.session.commit()
        return redirect(url_for('.dic_index'))
    db.session.close()
    return render_template('dictionary/edit_word.html', form=form, disease=disease, R=CodeRange())


@main.route('/dictionary/search', methods=['POST'])  # 精确查询接口（根据疾病名称查询）
@login_required
def search():
    name = request.json.get('name')
    disease = Dictionary.query.filter_by(name=name).first()
    if disease is None:
        result = dict(flag=0, message='未查询到该词，该词可能为新词')
    else:
        result = dict(flag=1, id=disease.id, code=disease.code, diseasename=disease.name,
                      description=disease.description)
    response = jsonify(result)
    return response


@main.route('/dictionary/change', methods=['POST'])  # 修词改接口
@login_required
def change():
    id = request.json.get('id')
    name = request.json.get('name')
    code = request.json.get('code')
    description = request.json.get('description')
    disease = Dictionary.query.filter_by(id=id).first()
    disease.name = name
    disease.code = code
    disease.description = description
    db.session.commit()
    result = dict(flag=1, message='修改成功')
    return jsonify(result)


@main.route('/dictionary/add', methods=['POST'])  # 添加新词接口
@login_required
def add():
    name = request.json.get('name')
    code = request.json.get('code')
    description = request.json.get('description')
    disease = Dictionary.query.filter_by(name=name).first()
    if disease is None:
        new_dissease = Dictionary(name=name, code=code, description=description)
        db.session.commit(new_dissease)
        result = dict(flag=1)
    else:
        result = dict(flag=0, message='该词已存在于词典')
    response = jsonify(result)
    return response


def CodeRange():
    words1 = Dictionary.query.filter(Dictionary.code.ilike('%DN%')).order_by(Dictionary.id).all()
    JB_code_F = words1[0].code
    JB_code_L = words1[-1].code
    # print(JB_code_F,JB_code_L)

    words2 = Dictionary.query.filter(Dictionary.code.ilike('%SS%')).order_by(Dictionary.id).all()
    ZZ_code_F = words2[0].code
    ZZ_code_L = words2[-1].code
    # print(ZZ_code_F,ZZ_code_L)

    words3 = Dictionary.query.filter(Dictionary.code.ilike('%DT%')).order_by(Dictionary.id).all()
    SJ_code_F = words3[0].code
    SJ_code_L = words3[-1].code
    # print(SJ_code_F,SJ_code_L)

    words4 = Dictionary.query.filter(Dictionary.code.ilike('%BP%')).order_by(Dictionary.id).all()
    BW_code_F = words4[0].code
    BW_code_L = words4[-1].code
    # print(BW_code_F,BW_code_L)

    words5 = Dictionary.query.filter(Dictionary.code.ilike('%MN%')).order_by(Dictionary.id).all()
    YP_code_F = words5[0].code
    YP_code_L = words5[-1].code
    # print(YP_code_F,YP_code_L)

    words6 = Dictionary.query.filter(Dictionary.code.ilike('%ON%')).order_by(Dictionary.id).all()
    SS_code_F = words6[0].code
    SS_code_L = words6[-1].code
    # print(SS_code_F,SS_code_L)

    words7 = Dictionary.query.filter(Dictionary.code.ilike('%EN%')).order_by(Dictionary.id).all()
    QX_code_F = words7[0].code
    QX_code_L = words7[-1].code
    # print(QX_code_F,QX_code_L)

    R = [JB_code_F, JB_code_L, ZZ_code_F, ZZ_code_L, SJ_code_F, SJ_code_L, BW_code_F, BW_code_L, YP_code_F, YP_code_L,
         SS_code_F, SS_code_L, QX_code_F, QX_code_L]
    return R
